import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { switchMap, map } from 'rxjs/operators';
import { Service } from '../../service/service';
import * as BookActions from '../actions/book.actions';

@Injectable()
export class BookEffects {
  loadBooks$ = createEffect(() =>
    this.actions$.pipe(
      ofType(BookActions.loadBooks),
      switchMap(() => this.bookService.getBooks()),
      map(books => BookActions.loadBooksSuccess({ books }))
    )
  );
  addBook$ = createEffect(() =>
    this.actions$.pipe(
      ofType(BookActions.addBook),
      switchMap(data => this.bookService.addBook(data.book)),
      map(book => BookActions.loadBooks())
    )
  );

  deleteBook$ = createEffect(() =>
    this.actions$.pipe(
      ofType(BookActions.deleteBook),
      switchMap(data => this.bookService.deleteBook(data.id)),
      map(book => BookActions.loadBooks())
    )
  );
  constructor(private actions$: Actions, private bookService: Service) {}
}
